<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\Permission;


class RoleController extends Controller
{
    //角色列表
    public function roleList(Request $request){
        $where = function ($query) use ($request) {
            //角色名
            if ($request->has('rolename') and $request->rolename != '') {
                $search = "%" . $request->rolename . "%";
                $query->where('rolename', 'like', $search);
            }

        };
        $allRole=Role::where($where)->with('permissions')->paginate(10);
        return view('admin.role.roleList',compact('allRole'));
    }

    //新建角色
    public function createRole(Request $request){
        return view('admin.role.createRole');
    }
    //保存角色
    public function saveRole(Request $request){
        return Role::checkRole($request);
    }

    //编辑角色
    public function editRole(Request $request){
        $arr=explode('=',$request->roleId);
        $roleId=$arr['1'];
        $editRole=Role::where('id',$roleId)->first();
        return view('admin.role.editRole',compact('editRole'));
    }

    //更新角色
    public function updateRole(Request $request){
        return Role::updateRole($request);
    }

    //删除角色
    public function deleteRole(Request $request){
        $deleteRole=Role::destroy($request->roleId);
        if($deleteRole){
            $backMsg=['msg'=>200];
            return json_encode($backMsg);
        }
    }

    //给角色添加权限
    public function addPermission(Request $request){
        $arr=explode('=',$request->roleId);
        $roleId=$arr['1'];
        $allPermission=Permission::all();
        return view('admin.role.addPermission',compact('allPermission','roleId'));
    }
    //给角色添加权限
    public function checkPermission(Request $request){
        return Role::checkPermission($request);
    }

}
